<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );

class JAJobBoardModelJAPermission extends JModel
{
	
	var $_data;
    var $_table;
    var $_pagination;
    
    /**
    * Return the query is used to retrive all row from database
    * @return string The query is used 
    */
    function getItems($group, $usergroup, $usertype){
    	global $mainframe;    	    	
    	
    	$db = &JFactory::getDBO();
    	
    	$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit',		'limit',		$mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( JBCOMNAME.'.japermission.limitstart',	'limitstart',	0, 'int' );
        //$filter_order		= $mainframe->getUserStateFromRequest( JBCOMNAME .".japermission.filter_order",		'filter_order',		'id',	'cmd' );
        $filter_order = JRequest::getVar('filter_order', 'u.id');
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( JBCOMNAME .".japermission.filter_order_Dir",	'filter_order_Dir',	'DESC',			'word' );
        $search				= $mainframe->getUserStateFromRequest( JBCOMNAME .".japermission.search",			'search',			'',				'string' );
		$search				= JString::strtolower( $search );
		
		$where = null;

		if($search){
			$where[] = " (u.name LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false )." or u.username LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false )." or u.email LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false ).")";			
		}		
		
        // just in case filter_order get's messed up
       
		if ($filter_order) {
			$orderby = ' ORDER BY '.$filter_order .' '. $filter_order_Dir;
		} else {
			$orderby = ' ORDER BY u.id DESC';
		}
        
        if($where)  $where = "\n WHERE ". implode(' and ', $where);
       
        $query = "SELECT u.*,us.*".
        		"\n FROM #__users as u  LEFT JOIN #__ja_permissions as us ON us.user_id=u.id".
        		$where.
        		$orderby;
		$db = &JFactory::getDBO();
		$db->setQuery($query);	//print_r($db->getQuery($query));exit;
		$items_temp = $db->loadObjectList();
		$items = array();
		if($items_temp){
    		foreach ($items_temp as $item) {
    			if ($usergroup=='admin')
    			{
    				
    				if (($usertype!='0')&&($usertype!=''))
    				{
    					if ($item->usertype==$usertype)
    						$items[] = $item;
    				}
    				else 
    				{
    					if (($item->usertype=='Administrator')||($item->usertype=='Super Administrator')||($item->usertype=='Magager'))
    						$items[] = $item;
    				}
    			}
    			else 
    			{
    				if (($item->usertype!='Administrator')&&($item->usertype!='Super Administrator'))
    					if ($usertype!='')
    					{
    						if ((getUserType($item->id)==$usertype))
    							$items[] = $item;
    					}
    					else 
    						$items[] = $item;
    			}
    		}
		}
		$total = count( $items );

		jimport('joomla.html.pagination');
		$this->_pagination = new JPagination( $total, $limitstart, $limit );
		
		$list = array();
		// slice out elements based on limits
		if($items)
		$list = array_slice( $items, $this->_pagination->limitstart, $this->_pagination->limit );
		
		return $list;
    }
    
    /**
	* Get page navigator object
	* @return 
	*/
	function &getPagination(){
		if ($this->_pagination == null) {
			$this->getItems();
		}
		return $this->_pagination;
	}
	
	// save a permission when edit or new.
	function store()	{
		global $jbconfig;
		
		$db	=	JFactory::getDBO();
		
		$post		= JRequest::get( 'post' );
		if (isset($post['cb']))
			$cbs		=	$post['cb'];
		else 	
			$cbs = null;
		$userid		=	$post['cid'];
		$user_permission	=	$post['user_per'];
		$user_permission_new	=	0;
		$usergroup = $post['usergroup'];
				
		if($cbs){
			foreach ($cbs as $c){
				$user_permission_new = (intval($user_permission_new)|$c);
			}
		}
		else 
		{
			$user_permission_new = 0;
		}

		if( $user_permission_new!=$user_permission ){		
			$query = "SELECT * FROM #__ja_permissions WHERE user_id='$userid'";				
			$db->setQuery($query);
			$result = $db->loadObjectList();
			if($result){
				$query = "UPDATE #__ja_permissions SET permission='$user_permission_new' WHERE user_id='$userid'";
			}
			else{
				$query = "INSERT INTO #__ja_permissions (permission, user_id) Values('$user_permission_new', '$userid')";	
			}
			
			$db->setQuery($query);
//					var_dump($db->getQuery());exit;
			if($db->query())
			{
				$msg = JText::_('Successfully updated permission');
			}
			else 
			{
				$msg = JText::_('Error found!Fail to save permission');
			}
		}
		else 
		{
			$msg = JText::_('This permission name is already available exist');
		}
			
		return $msg;
	}
	
	// save a permission when edit or new.
	function store_group()	{
		global $jbconfig;
		
		$db	=	JFactory::getDBO();
		
		$post		= JRequest::get( 'request' );
		
		$cbs		=	$post['cb'];
		$group_permission	=	isset($post['group_per'])?$post['group_per']:0;
		$group_permission_new	=	0;
		$usertype = $post['usertype'];
		$group = str_replace(' ', '_', $usertype.'_permission');
			
		if($cbs){
			foreach ($cbs as $c){
				$group_permission_new = (intval($group_permission_new)|$c);
			}
		}
		
		$group_permission_old = isset($jbconfig['group_permission'])?$jbconfig['group_permission']->get($group, '0'):0;
		if( $group_permission_new==$group_permission_old  &&  $group_permission_old>0){
			$msg=JText::_('Successfully updated permission for guest');
		}
		else {				
			$paramsField = isset($jbconfig['group_permission'])?$jbconfig['group_permission']->_registry['_default']['data']:'';
			$params = new JParameter('');
			$data = array();
			$check = false;
			foreach ($paramsField as $k => $v){
				if( $k==$group ){
					$v = $group_permission_new;
					$check = true;
				}
				$params->set($k, $v);
				
			}
			if (!$check) {
				$params->set($group, $group_permission_new);
			}
			
			$data = $db->Quote($params->toString());
			if(isset($jbconfig['group_permission'])){
				$query	=	"UPDATE #__ja_config SET data=$data WHERE tab='group_permission'";
			}
			else{
				$query	=	"INSERT INTO #__ja_config  (`data`,`tab`) values ($data,'group_permission')";
			}
			$db->setQuery($query);
			
			if($db->query())
				return JText::_('Successfully updated permission for guest');
			else 
			{
				
				JError::raiseWarning(1, JText::_('Error found!Fail to update permission for guest'));	
			}
					
		}
						
		return ;
	}
	function initial_per()
	{
		global $jbconfig;
		$user = & JFactory::getUser();
		$usertype = str_replace(' ', '_', getCurrentUserType());
		$initial_per = $jbconfig['group_permission']->get($usertype.'_permission');
		$db = & JFactory::getDBO();
		//Check existing permission
		$query = 'SELECT * FROM #__ja_permissions WHERE user_id='.$user->id;
		$db->setQuery($query);
		$item = $db->loadObjectList();
		if (!is_array($item))
			$query = 'INSERT INTO #__ja_permissions VALUES ('.$user->id.','.$initial_per.')';
		else 
			$query = 'UPDATE #__ja_permissions SET permission='.$initial_per.' WHERE user_id='.$user->id;
		$db->setQuery($query);
		$db->query();
	}	
}